# -*- coding: utf-8 -*-
'''
Created on 2012/06/21

@author: harendra
'''
import instapaperlib
import urllib2
from xml.dom.minidom import parse,parseString
import feedparser

def getTitlesLinks(link):
    titles=[]
    links=[]
    parsed=feedparser.parse(link)
    if parsed['bozo']==1:
        return [],[]
    for item in parsed['items']:
        titles.append(item['title'])
        links.append(item['link'])
    return titles,links   

def sendarticles(titles,links):  
    for i in range(len(titles)):
        print "adding "+titles[i]
        instapaperlib.auth('harendra007@gmail.com','18918848')
        instapaperlib.add_item('harendra007@gmail.com','18918848',links[i],titles[i])

def removeduplicates(oldlinks,newlinks,titles):    
    filteredlinks=[]
    filteredtitles=[]
    for link in newlinks:
        try:
            if oldlinks.index(link)!=-1:
                pass
        except:
            filteredlinks.append(link)
            oldlinks.append(link)
            filteredtitles.append(titles[newlinks.index(link)])
    return filteredlinks,filteredtitles,oldlinks

def sendLink(link,storedfile):
    oldlinklist=readlinesFromFile(storedfile)
    titles,links=getTitlesLinks(link)
    filteredlinks,filteredtitles,oldlinks=removeduplicates(oldlinklist,links,titles)
    print filteredlinks
    print filteredtitles
    sendarticles(filteredtitles,filteredlinks)
    writeListToFile(storedfile,oldlinks)
    

def startsending():
    arstechnicalinksfile="arstechnicalinks"
    arstechnicalink="http://feeds.arstechnica.com/arstechnica/index/"
    wiredlinksfile="wiredlinks"
    wiredlink="http://feeds.wired.com/wired/index"
    vergelinksfile="vergelinks"
    vergelink="http://www.theverge.com/rss/index.xml"
    cricinfolinksfile="cricinfolinks"
    cricinfolink="http://www.espncricinfo.com/rss/content/story/feeds/0.xml"
    
    sendLink(arstechnicalink,arstechnicalinksfile)
    sendLink(wiredlink,wiredlinksfile)
    sendLink(vergelink,vergelinksfile)
    sendLink(cricinfolink,cricinfolinksfile)

def readlinesFromFile(filename):
    try:
        f=open(filename)
        data= f.read()
        links=data.split('\n')
        return links
    except:
        return []
    

def writeListToFile(filename,datalist):
    f=open(filename,'w')
    listtext=""
    for data in datalist:
        listtext+=data.strip()+"\n"
    f.write(listtext)
    
startsending()
